# RBC教材第四章可变劳动的例子


using Pipe, Statistics, JLD2, Optim
using BenchmarkTools

include("ValIte.jl")
# 参数设置
deltax = 0.1
thetax = 0.36
betax = 0.98
A = 0.5

# 数值计算设置
crit = 1
tol = 0.001
eps = 0.02

# 格点和值函数初值设置和下一期最优资本存量内存分配
k0 = LinRange(0.06,10,80) |> collect
aopt = zeros(length(k0))
v = LinRange(-4,9,length(k0)) |> collect


# 迭代循环直至收敛
# @time begin
    j = 0
    while crit > tol
        global j += 1
        println(crit)
        vold = copy(v)
        m = 0
        for i in range(1,length(k0))
            ainit = k0[i]
            v0 = 1e10
            m = m + 1
            blm = para_cmp(ainit, k0, vold,
                thetax = thetax, deltax = deltax, betax = betax, A = A)
            pos = decise_range(blm, k0, m, k0[m])
            m = pos.m0

            # 给定a1范围，找到考虑边界点的最大值函数对应的a1
            pos2 = pairs(pos) |> Dict
            global aopt[i] = searmax(blm, pos2, eps = eps, agrid = k0,vold = vold)
            global v[i] = -blm(aopt[i])
        end
        global crit = abs.(vold-v) |> mean |> max
    end
# end


# JLD2.jldsave("value_ite.jld2")
